package com.beasts.ant.auth.controller;

import com.beasts.ant.auth.common.constant.SecurityConstants;
import com.beasts.ant.auth.common.dto.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * oauth2 相关入口
 *
 * @author Locker
 * @date 08/05/2018 10:44 AM
 * @since 1.0
 */
@Api(value = "/authentication", tags = "获取oauth_token后的相关操作")
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {

    @Autowired
    @Qualifier("consumerTokenServices")
    private ConsumerTokenServices consumerTokenServices;

    // /oauth/token

    /**
     * 用户信息校验
     */
    @ApiOperation(value = "获取用户信息", notes = "需要access_token")
    @ApiImplicitParam(name = "access_token", dataType = "String")
    @PostMapping("/userInfo")
    public Object user(Authentication authentication) {
        return authentication.getPrincipal();
    }

    /**
     * 清除 access_token
     */
    @ApiOperation(value = "删除指定access_token", notes = "需要access_token")
    @ApiImplicitParam(name = "access_token", dataType = "String")
    @PostMapping("/removeToken")
    @CacheEvict(value = SecurityConstants.TOKEN_USER_DETAIL, key = "#access_token")
    public R<Boolean> removeToken(String access_token) {
        return new R<>(consumerTokenServices.revokeToken(access_token));
    }

}
